package cn.icanci.loopstack.rec.engine.script.factory;

import cn.icanci.loopstack.rec.engine.script.enums.ScriptTypeFactoryEnum;
import cn.icanci.loopstack.rec.common.enums.ScriptTypeEnum;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.script.ScriptEngine;

/**
 * @author icanci
 * @since 1.0 Created in 2022/11/13 12:18
 */
public final class ScriptEngineFactory {

    /**
     * 只有一个实例
     */
    private static final Map<ScriptTypeEnum, ScriptEngine> SCRIPT_ENGINE_CACHE = new ConcurrentHashMap<>();

    static {
        ScriptTypeFactoryEnum[] scriptTypeFactory = ScriptTypeFactoryEnum.values();
        for (ScriptTypeFactoryEnum factory : scriptTypeFactory) {
            // ConcurrentHashMap#key、value can not be null !!!
            SCRIPT_ENGINE_CACHE.put(factory.getScriptType(), factory.getFactory().getScriptEngine());
        }
    }

    /**
     * 根据 scriptType 类型获取执行引擎
     * 
     * @param scriptType scriptType
     * @return 返回执行引擎
     */
    public static ScriptEngine getScriptEngine(ScriptTypeEnum scriptType) {
        return SCRIPT_ENGINE_CACHE.get(scriptType);
    }
}
